
//新的表
const { Class_description } = require('../models/Course outline/Class_description')
const { Beginning } = require('../models/Course outline/beginning')
const { Index_Point } = require('../models/Course outline/index_Point')


//有所改动
const { T_exam_target } = require('../models/t_exam_target')
const { Weight_Support_link } = require('../models/Course outline/weight_Support_link')

//之前的表（无改动）
const { T_exam_target_to_question } = require('../models/t_exam_target_to_question')
const { T_exam_label } = require('../models/t_exam_label')
const { t_label_to_realLabel } = require('../models/T_label_to_realLabel')
const { Op } = require('sequelize')

const powerEnum = {
  "L": 0.2,
  "M": 0.3,
  "H": 0.4
}

const supportLinkEnum = {
  1: "作业",
  2: "课堂表现",
  3: "试卷集合"
}


exports.getTargetNum = async (req, res) => {
  const { ACSId } = req.query

  try {
    const targetNum = await T_exam_target.findAll({
      where: {
        t_user_and_a_c_s_id: ACSId,
      },
    })

    res.json({
      "code": 200,
      "targetNum": targetNum.length
    })

  } catch (error) {
    res.json({
      "code": 500,
      "targetNum": "error"
    })
  }

}


exports.getCourseAchievement = async (req, res) => {
  const { subId, ACSID, paperType } = req.query


  //第一   一、课程基本信息
  //通过ACSID
  let tempBeginning = await Beginning.findOne({
    where: {
      t_user_and_a_c_s_id: ACSID
    },
    attributes: ['Leader']
  });

  let tempClassDescription = await Class_description.findOne({
    where: {
      t_user_and_a_c_s_id: ACSID,

    },
    attributes: ['code', 'cName', 'creAndHours', 'quality']
  });


  let returnClassMes
  if (tempBeginning && tempClassDescription) {
    returnClassMes = ([
      { item: '课程编号', content: tempClassDescription.code },
      { item: '课程名称', content: tempClassDescription.cName },
      { item: '学时/学分', content: tempClassDescription.creAndHours },
      { item: '课程性质', content: tempClassDescription.quality },
      { item: '开课学期', content: "无" },
      { item: '授课对象', content: tempBeginning.Leader },
      { item: '授课人数', content: "无" },
      { item: '任课教师（职称）', content: "无" },
    ])
  }



  // 第二    该课程各个课程目标及权重值的确定
  //通过subId
  // let returnTarget = []



  // const Target = await T_exam_target.findAll({
  //   where: {
  //     sub_id: subId
  //   },
  //   attributes: ['point_id', 'point_deep', 'target_name', 'target_content'],
  //   include: [{
  //     model: Index_Point, // 关联的模型
  //     attributes: ['point_content', 'point_name'], // 需要查询的属性
  //     as: 'Index_Point' // 关联的别名
  //   }]
  // });

  let returnTargetPoint = []
  const { Index_Point } = require('../models/Course outline/index_Point')
  const { class_Target_AND_Point } = require('../models/Course outline/class_Target_AND_Point')
  //通过acsid
  const link = await class_Target_AND_Point.findAll({
    where: {
      t_user_and_a_c_s_id: ACSID
    }
  });


  const Target = await Promise.all(link.map(async item => {
    const point = await Index_Point.findOne({
      where: {
        t_user_and_a_c_s_id: ACSID,
        point_name: item.index_point_name
      }
    });

    // console.log(point);

    const target = await T_exam_target.findOne({
      where: {
        t_user_and_a_c_s_id: ACSID,
        target_name: item.class_target_name
      },
      attributes: ['target_name', 'target_desc', 'target_content']
    });

    // console.log("hehehehehe");
    // console.log("hahahahha", target);
    if (target && point) {
      return {
        point_id: point.id,
        point_deep: item.between,
        target_name: target.target_name,
        target_content: target.target_content,
        Index_Point: {
          point_content: point.point_content,
          point_name: point.point_name
        }
      };
    } else {
      return {
        error: "hh"
      }
    }

  }));

  if (Target.length > 0) {
    // 找到了匹配的数据

    // 将查询结果封装为对象数组
    returnTarget = Target.map(item => ({
      targetName: item.target_name,
      targetContent: item.target_content
    }));

    returnTargetPoint = Target.map(item => ({
      // point_id: item.point_id,
      // pointDeep: item.point_deep,
      targetName: item.target_name,
      pointContent: item.Index_Point ? item.Index_Point.point_content : null,
      pointName: item.Index_Point ? item.Index_Point.point_name : null,
      pointDeep: item.point_deep
    }));



  }
  console.log("returntarget", returnTarget)
  // console.log("returnTargetPoint", returnTargetPoint);


  // //第三  课程目标达成度定量分析
  //通过ACSID
  let returnAssessment = []

  const assessment = await Weight_Support_link.findAll({
    where: {
      t_user_and_a_c_s_id: ACSID
    },
    attributes: ['class_target_name', 'suppore', 'weight']
  })
  // console.log(assessment);


  if (assessment.length > 0) {
    returnAssessment = assessment.map(item => ({
      supportLink: item.suppore,
      weight: item.weight,
      courseObjective: item.class_target_name
    }))
  }

  // console.log("returnassessment", returnAssessment);


  //第四  （三）支撑环节3--期末考试
  //通过subId,paperType
  const newData = {};


  const targetMes = await T_exam_target.findAll({
    where: {
      t_user_and_a_c_s_id: ACSID,
    },
    attributes: ['id', 'target_desc', 'target_content', 'target_name']
  })
  const targetMap = targetMes.reduce((acc, cur) => {
    acc[cur.id] = cur.target_name;
    return acc;
  }, {});
  const targetDetileMes = await T_exam_target_to_question.findAll({
    where: {
      t_user_and_a_c_s_id: ACSID,
      paperType: paperType
    },
    attributes: ['targetId', 'score', 'questionType']
  })

  // console.log("dgqwghowhgo急急急", targetDetileMes);

  const totalScoresByTargetId = targetDetileMes.reduce((acc, cur) => {
    const { targetId, score } = cur;
    if (acc[targetId]) {
      acc[targetId] += score;
    } else {
      acc[targetId] = score;
    }
    return acc;
  }, {});



  for (const key in totalScoresByTargetId) {
    if (key in targetMap) {
      const targetName = targetMap[key];
      newData[targetName] = totalScoresByTargetId[key];
    }
  }

  console.log(newData);

  const arrayFromObject = Object.entries(newData).map(([targetName, targetScore]) => ({ targetName, targetScore }));
  // console.log(arrayFromObject);



  //处理完数据库数据后获取前端数据并解析
  const DataToSubmit = req.body.DataToSubmit
  const studentCount = req.body.studentCount


  //这个是返回的数据
  let returnnewArray = []

  if (studentCount && DataToSubmit) {
    returnnewArray = arrayFromObject.map(({ targetName, targetScore }) => {
      const correspondingResult = DataToSubmit.find(result => result.type === targetName);
      if (correspondingResult) {
        const { score } = correspondingResult;
        const calculatedTargetScore = score / targetScore;
        return { courseObjective: targetName, totalValue: targetScore, averageScore: score, completion: calculatedTargetScore };
      }
      return { courseObjective: targetName, totalValue: targetScore };
    });
  }



  // targetName: item.target_name,
  // pointContent: item.point ? item.Index_Point.point_content : null,
  // pointDeep: item.point ? item.Index_Point.point_name : null




  //（二）支撑环节2--课程作业
  let returnTaskMes = []
  if (returnTargetPoint && DataToSubmit) {
    returnTaskMes = returnTargetPoint.map(({ targetName, pointDeep }) => {
      const correspondingResult = DataToSubmit.find(result => result.type === targetName);
      if (correspondingResult) {
        const { taskScore } = correspondingResult;
        const calculatedTargetScore = taskScore / (powerEnum[pointDeep] * 100);
        return { courseObjective: targetName, totalValue: powerEnum[pointDeep] * 100, averageScore: taskScore, completion: calculatedTargetScore };
      }
      return { courseObjective: targetName, totalValue: powerEnum[pointDeep] * 100 };
    });
  }

  //支撑环节（一）支撑环节1--课堂表现
  let returnCorseMes = []
  if (returnTargetPoint && DataToSubmit) {
    returnCorseMes = returnTargetPoint.map(({ targetName, pointDeep }) => {
      const correspondingResult = DataToSubmit.find(result => result.type === targetName);
      if (correspondingResult) {
        const { courseScore } = correspondingResult;
        const calculatedTargetScore = courseScore / (powerEnum[pointDeep] * 100);
        return { courseObjective: targetName, totalValue: powerEnum[pointDeep] * 100, averageScore: courseScore, completion: calculatedTargetScore };
      }
      return { courseObjective: targetName, totalValue: powerEnum[pointDeep] * 100 };
    });
  }

  //（四）课程目标达成度
  // const supportLinkEnum = {
  //   1: "作业",
  //   2: "课堂表现",
  //   2: "试题集合"
  // }

  //supportLink: item.content,
  //weight: item.proportion,
  //courseObjective: item.target.target_name

  let returnTargetAchievement = []
  returnTargetAchievement = returnTarget.map(({ targetName }) => {

    // console.log(targetName);

    const assessmentMes = returnAssessment.filter(result => result.courseObjective === targetName);
    if (assessmentMes) {
      const taskTarget = assessmentMes.find(result => result.supportLink === supportLinkEnum[1])
      const courseTarget = assessmentMes.find(result => result.supportLink === supportLinkEnum[2])
      const examTarget = assessmentMes.find(result => result.supportLink === supportLinkEnum[3])

      let supportLinks = ""

      let score = 0
      // console.log(examTarget);

      if (taskTarget) {
        const task = returnTaskMes.find(result => result.courseObjective === targetName)
        // console.log(task);
        if (task) {
          // console.log("task", task.completion * taskTarget.weight);
          console.log(task.completion, "  *  ", taskTarget.weight);

          score += task.completion * taskTarget.weight
          supportLinks += "作业 "
        }
      }

      if (courseTarget) {
        const course = returnCorseMes.find(result => result.courseObjective === targetName)
        if (course) {
          console.log("course", course.completion);
          score += course.completion * courseTarget.weight
          supportLinks += "课堂表现 "
        }
      }

      if (examTarget) {
        const exam = returnnewArray.find(result => result.courseObjective === targetName)
        if (exam) {

          console.log("exam", exam.completion);
          score += exam.completion * examTarget.weight
          supportLinks += "试卷集合 "
        }
      }

      return {
        "courseObjective": targetName,
        "supportLinks": supportLinks,
        "completion": score
      }
    }

  })


  res.json({
    "code": 200,
    "content": {
      returnClassMes,
      returnTarget,
      returnTargetPoint,
      returnAssessment,
      returnnewArray,
      returnTaskMes,
      returnCorseMes,
      returnTargetAchievement
    }
  })







}


exports.getPaperInfoAchievement = async (req, res) => {
  const ACSId = req.query.ACSId
  const subId = req.query.subId
  try {
    const mes = await T_exam_target_to_question.findAll({
      where: {
        t_user_and_a_c_s_id: ACSId,

      }
    });

    console.log(mes.length);

    const objA = {}
    const objB = {}
    if (mes.length !== 0) {
      for (let i = 0; i < mes.length; i++) {
        // console.log("ajajjajaja  i=", i);

        console.log(mes[i].targetId);
        const labelId = await t_label_to_realLabel.findAll({
          where: {
            target_id: mes[i].targetId
          },
          attributes: ['label_id']
        })
        const labelIdArray = labelId.map(item => item.label_id)
        const taregtName = await T_exam_target.findOne({
          where: {
            id: mes[i].targetId
          },
          attributes: ['target_name']
        })

        // console.log("targetName = !!!", taregtName);

        const data = await T_exam_label.findAll({
          where: {
            id: { [Op.in]: labelIdArray }
          },
          attributes: ['label'],
          // include: [{
          //   model: T_exam_target, // 关联的模型
          //   attributes: ['target_name'], // 需要查询的属性
          //   as: 'T_exam_target' // 关联的别名
          // }]
        })


        // console.log("哈哈哈data = ", data);
        const array = []
        if (data.length != 0) {
          // console.log(data);

          data.forEach(item => {
            array.push(item.label)
          })
        }
        if (taregtName) {
          if (mes[i].dataValues.paperType === 'A') {
            if (!objA[taregtName.target_name]) {
              // console.log(objA);
              objA[taregtName.target_name] = {}
              objA[taregtName.target_name].targetName = taregtName.target_name
              objA[taregtName.target_name].target_desc = array
              objA[taregtName.target_name].score = 0
              objA[taregtName.target_name].typeAndOrder = []
              // console.log(objA);
            }
            objA[taregtName.target_name].typeAndOrder.push(mes[i].dataValues.questionType + "  共" + mes[i].dataValues.questionNum + "题 (每题" + mes[i].dataValues.score / mes[i].dataValues.questionNum + "分）")
            objA[taregtName.target_name].score += mes[i].dataValues.score
            console.log("objA = !!!", objA);
          } else if (mes[i].dataValues.paperType === 'B') {

            if (!objB[taregtName.target_name]) {
              // console.log(objA);
              objB[taregtName.target_name] = {}
              objB[taregtName.target_name].targetName = taregtName.target_name
              objB[taregtName.target_name].target_desc = array
              objB[taregtName.target_name].score = 0
              objB[taregtName.target_name].typeAndOrder = []
              // console.log(objA);
            }
            objB[taregtName.target_name].typeAndOrder.push(mes[i].dataValues.questionType + "  共" + mes[i].dataValues.questionNum + "题 (每题" + mes[i].dataValues.score / mes[i].dataValues.questionNum + "分）")
            objB[taregtName.target_name].score += mes[i].dataValues.score
            console.log("objB = !!!", objB);
          }
        } else {

        }



      }


      const keyA = Object.keys(objA)
      const A = []
      keyA.map(item => {
        A.push(objA[item])
      })

      const keyB = Object.keys(objB)
      const B = []
      keyB.map(item => {
        B.push(objB[item])
      })
      return res.json({
        "code": 200,
        "content": {
          A,
          B
        }
      });
    } else {
      return res.json({
        "code": 200,
        "content": '无数据'
      });
    }
  } catch (error) {
    res.json({
      "code": 500,
      "content": error.msg
    });
  }
}